<template>
  <div class="container">
    <Breadcrumb :items="['合伙人管理', '合伙人列表']" />
    <a-card class="general-card" :title="$t('合伙人列表')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="partnerName" :label="$t('合伙人名称')">
                  <a-input
                    v-model="searchForm.partnerName"
                    :placeholder="$t('请输入合伙人名称')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="contactName" :label="$t('联系人')">
                  <a-input
                    v-model="searchForm.contactName"
                    :placeholder="$t('请输入联系人姓名')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="contactPhone" :label="$t('联系电话')">
                  <a-input
                    v-model="searchForm.contactPhone"
                    :placeholder="$t('请输入联系电话')"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="partnerType" :label="$t('合伙人类型')">
                  <a-select
                    v-model="searchForm.partnerType"
                    :placeholder="$t('请选择合伙人类型')"
                    allow-clear
                  >
                    <a-option :value="PartnerTypeEnum.PERSONAL">加盟</a-option>
                    <a-option :value="PartnerTypeEnum.ENTERPRISE"
                      >购买</a-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" :label="$t('状态')">
                  <a-select
                    v-model="searchForm.status"
                    :placeholder="$t('请选择状态')"
                    allow-clear
                  >
                    <a-option :value="StatusEnum.ENABLED">启用</a-option>
                    <a-option :value="StatusEnum.DISABLED">禁用</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="16">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                  <a-button
                    type="primary"
                    status="success"
                    @click="openCreateForm"
                  >
                    <template #icon>
                      <icon-plus />
                    </template>
                    {{ $t('新增合伙人') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="id"
        :loading="loading"
        :data="renderData"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="false"
      >
        <template #columns>
          <a-table-column title="合伙人名称" data-index="realName">
            <template #cell="{ record }">
              <a-link @click="viewDetail(record)">{{ record.realName }}</a-link>
            </template>
          </a-table-column>
          <a-table-column title="合伙人类型" data-index="source">
            <template #cell="{ record }">
              {{ getPartnerTypeName(record.source) }}
            </template>
          </a-table-column>
          <a-table-column title="角色" data-index="partnerRole">
            <template #cell="{ record }">
              {{ getPartnerRoleName(record.partnerRole) }}
            </template>
          </a-table-column>
          <a-table-column title="手机号码" data-index="mobile" />
          <a-table-column title="状态" data-index="enabled">
            <template #cell="{ record }">
              <a-tag :color="record.enabled ? 'green' : 'red'">
                {{ record.enabled ? '启用' : '禁用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createDate">
            <template #cell="{ record }">
              {{ formatDateTime(record.createDate) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="200">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="viewDetail(record)">
                  查看
                </a-button>
                <a-button
                  type="text"
                  size="small"
                  @click="openEditForm(record)"
                >
                  编辑
                </a-button>
                <a-button
                  type="text"
                  size="small"
                  :status="record.enabled ? 'danger' : 'success'"
                  @click="toggleStatus(record)"
                >
                  {{ record.enabled ? '禁用' : '启用' }}
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 合伙人表单对话框 -->
    <a-modal
      v-model:visible="formVisible"
      :title="formTitle"
      :width="900"
      @before-ok="handleSubmitForm"
      unmount-on-close
    >
      <partner-form ref="formRef" :form-data="formData" :is-edit="isEdit" />
      <template #footer>
        <a-space>
          <a-button @click="formVisible = false">取消</a-button>
          <a-button type="primary" @click="manualSubmitForm"> 确定 </a-button>
        </a-space>
      </template>
    </a-modal>

    <!-- 合伙人详情对话框 -->
    <partner-detail
      v-model:visible="detailVisible"
      :partner-data="detailInfo"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import {
    getPartnerList,
    getPartnerDetail,
    addPartner,
    updatePartner,
    enablePartner,
    disablePartner,
    Partner,
    PartnerTypeEnum,
    PartnerRoleEnum,
    StatusEnum,
    AccountStatusEnum,
  } from '@/api/partner';
  import dayjs from 'dayjs';
  import {
    IconSearch,
    IconRefresh,
    IconPlus,
  } from '@arco-design/web-vue/es/icon';
  import PartnerForm from './components/partner-form.vue';
  import PartnerDetail from './components/partner-detail.vue';

  const { loading, setLoading } = useLoading();
  const renderData = ref<Partner[]>([]);
  const formRef = ref();
  const formVisible = ref(false);
  const isEdit = ref(false);
  const formData = ref<Partial<Partner>>({});
  const detailVisible = ref(false);
  const detailInfo = ref<Partial<Partner>>({});

  const searchForm = reactive({
    partnerName: '',
    contactName: '',
    contactPhone: '',
    partnerType: undefined as number | undefined,
    status: undefined as number | undefined,
  });

  const pagination = reactive({
    total: 0,
    current: 1,
    pageSize: 10,
    showTotal: true,
    showPageSize: true,
    pageSizeOptions: [10, 20, 50],
  });

  const formTitle = computed(() => {
    return isEdit.value ? '编辑合伙人' : '新增合伙人';
  });

  // 格式化日期时间
  function formatDateTime(date: string | undefined) {
    if (!date) return '-';
    return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
  }

  // 获取合伙人类型名称
  function getPartnerTypeName(type: number | undefined) {
    if (type === undefined) return '-';
    const typeMap = {
      [PartnerTypeEnum.PERSONAL]: '加盟',
      [PartnerTypeEnum.ENTERPRISE]: '购买',
    };
    return typeMap[type as keyof typeof typeMap] || '-';
  }

  // 获取合伙人角色名称
  function getPartnerRoleName(role: number | undefined) {
    if (role === undefined) return '-';
    const roleMap = {
      [PartnerRoleEnum.COMPANY]: '公司合伙人',
      [PartnerRoleEnum.MARKET]: '市场合伙人',
      [PartnerRoleEnum.MANAGER]: '管理合伙人',
      [PartnerRoleEnum.COMMISSION]: '分佣合伙人',
    };
    return roleMap[role as keyof typeof roleMap] || '-';
  }

  // 查询数据
  async function fetchData() {
    setLoading(true);
    try {
      const params = {
        ...searchForm,
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
      };

      const res = await getPartnerList(params);
      if (res.code === 200) {
        renderData.value = res.data.records;
        pagination.total = res.data.total;
        pagination.current = res.data.current;
      }
    } catch (err) {
      console.error('获取合伙人列表出错:', err);
      Message.error('获取合伙人列表失败');
    } finally {
      setLoading(false);
    }
  }

  // 查看详情
  async function viewDetail(record: Partner) {
    try {
      const res = await getPartnerDetail(record.id);
      detailInfo.value = res.data;
      detailVisible.value = true;
    } catch (err) {
      console.error('获取合伙人详情出错:', err);
      Message.error('获取合伙人详情失败');
    }
  }

  // 开启新增表单
  function openCreateForm() {
    isEdit.value = false;
    formData.value = {
      source: PartnerTypeEnum.PERSONAL,
      enabled: true,
      partnerRole: PartnerRoleEnum.MARKET,
    };
    formVisible.value = true;
  }

  // 开启编辑表单
  async function openEditForm(record: Partner) {
    try {
      const res = await getPartnerDetail(record.id);
      formData.value = res.data;
      isEdit.value = true;
      formVisible.value = true;
    } catch (err) {
      console.error('获取合伙人详情出错:', err);
      Message.error('获取合伙人详情失败');
    }
  }

  // 切换合伙人状态
  async function toggleStatus(record: Partner) {
    const newStatus = !record.enabled;
    const actionName = newStatus ? '启用' : '禁用';

    Modal.confirm({
      title: `确认${actionName}`,
      content: `您确定要${actionName}合伙人 "${record.realName}" 吗？`,
      onOk: async () => {
        try {
          if (newStatus) {
            await enablePartner(record.id);
          } else {
            await disablePartner(record.id);
          }
          Message.success(`${actionName}成功`);
          fetchData();
        } catch (err) {
          console.error(`${actionName}合伙人出错:`, err);
          Message.error(`${actionName}失败`);
        }
      },
    });
  }

  // 提交表单
  async function handleSubmitForm(done: any) {
    try {
      if (!formRef.value) {
        Message.error('表单引用不存在');
        done(false);
        return;
      }

      const valid = await formRef.value.validate();

      if (valid === true) {
        const result = await formRef.value.submit();

        if (result) {
          Message.success(`${isEdit.value ? '编辑' : '新增'}合伙人成功`);
          fetchData();
          done();
        } else {
          Message.error(`${isEdit.value ? '编辑' : '新增'}合伙人失败`);
          done(false);
        }
      } else {
        Message.warning('表单验证未通过，请检查表单内容');
        done(false);
      }
    } catch (err) {
      console.error('提交合伙人表单出错:', err);
      Message.error(`${isEdit.value ? '编辑' : '新增'}合伙人失败`);
      done(false);
    }
  }

  // 手动提交表单
  async function manualSubmitForm() {
    try {
      if (!formRef.value) {
        Message.error('表单引用不存在');
        return;
      }

      const valid = await formRef.value.validate();

      if (valid === true) {
        const result = await formRef.value.submit();

        if (result) {
          Message.success(`${isEdit.value ? '编辑' : '新增'}合伙人成功`);
          formVisible.value = false;
          fetchData();
        } else {
          Message.error(`${isEdit.value ? '编辑' : '新增'}合伙人失败`);
        }
      } else {
        Message.warning('表单验证未通过，请检查表单内容');
      }
    } catch (err) {
      console.error('手动提交出错:', err);
      Message.error(`提交失败，请检查表单`);
    }
  }

  // 搜索
  function search() {
    pagination.current = 1;
    fetchData();
  }

  // 重置
  function reset() {
    searchForm.partnerName = '';
    searchForm.contactName = '';
    searchForm.contactPhone = '';
    searchForm.partnerType = undefined;
    searchForm.status = undefined;
    pagination.current = 1;
    fetchData();
  }

  function onPageChange(current: number) {
    pagination.current = current;
    fetchData();
  }

  function onPageSizeChange(pageSize: number) {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
  }

  // 初始化
  onMounted(() => {
    fetchData();
  });
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .general-card {
    :deep(.arco-card-header) {
      border-bottom: 1px solid var(--color-border-2);
      padding: 16px 20px;
    }
  }
</style>
